package io.wdb.modules.generator.generator.service.impl.operation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;

import io.wdb.common.utils.DateFormatUtil;
import io.wdb.common.utils.PageHelperUtil;
import io.wdb.common.utils.Query;
import io.wdb.modules.generator.generator.dao.BookEntityDao;
import io.wdb.modules.generator.generator.dao.BookGridTransDao;
import io.wdb.modules.generator.generator.dao.BookgridInfoDao;
import io.wdb.modules.generator.generator.dao.BookshelfInfoDao;
import io.wdb.modules.generator.generator.dao.LampStrategyDao;
import io.wdb.modules.generator.generator.dao.OrderTransDao;
import io.wdb.modules.generator.generator.dao.ProcessInstructionLogDAO;
import io.wdb.modules.generator.generator.entity.BookEntityEntity;
import io.wdb.modules.generator.generator.entity.BookGridTransEntity;
import io.wdb.modules.generator.generator.entity.BookgridInfoEntity;
import io.wdb.modules.generator.generator.entity.BookshelfInfoEntity;
import io.wdb.modules.generator.generator.entity.LampStrategyEntity;
import io.wdb.modules.generator.generator.entity.ProcessInstructionLogDO;
import io.wdb.modules.generator.generator.entity.customer.BookEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.BookShelfInfoEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.ProcessCheckRes;
import io.wdb.modules.generator.generator.entity.customer.ProcessInstructionLogCustomer;
import io.wdb.modules.generator.generator.entity.statistics.LampStrategyRes;
import io.wdb.modules.generator.generator.entity.web.BookGridsStatus;
import io.wdb.modules.generator.generator.entity.web.BookShelfLoRes;
import io.wdb.modules.generator.generator.entity.web.BookShelfOperation;
import io.wdb.modules.generator.generator.entity.web.DaysQueryRequest;
import io.wdb.modules.generator.generator.entity.web.OperationResponse;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.operation.BookShelfOperationService;
import io.wdb.modules.manager.gen.manager.BookGridManager;
import io.wdb.modules.manager.gen.manager.WSBookShelfEnum;
import io.wdb.modules.manager.sys.entity.SysUserEntity;

@Service
public class BookShelfOperationServiceImpl implements BookShelfOperationService{
	private Logger logger = LoggerFactory.getLogger(BookShelfOperationServiceImpl.class);
	@Autowired
	private BookshelfInfoDao bookshelfInfoDao;
	
	@Autowired
	private BookEntityDao bookEntityDao;
	
	@Autowired
	private BookgridInfoDao bookgridInfoDao;
	
	@Autowired
	private BookGridManager bookGridManager;
	
	@Autowired
	private BookGridTransDao bookGridTransDao;
	
	@Autowired
	private ProcessInstructionLogDAO processInstructionLogDAO;
	
	@Autowired
	private LampStrategyDao lampStrategyDao;
	
	@Autowired
	private OrderTransDao orderTransDao;
	@Override
	public List<BookShelfInfoEntityCustomer> list(Query query) {
		PageHelper.startPage(PageHelperUtil.getPageNum(query),PageHelperUtil.getPageSize(query));
		List<BookShelfInfoEntityCustomer> bookshelfInfoEntities = bookshelfInfoDao.queryShelfList(query);
		for(BookShelfInfoEntityCustomer bookShelfInfoEntityCustomer:bookshelfInfoEntities) {
			bookShelfInfoEntityCustomer.setCashAddress(bookShelfInfoEntityCustomer.getArea()+bookShelfInfoEntityCustomer.getAddress());
			//当前书籍数量
			Integer currentBookCount = bookEntityDao.queryCurrentBookCount(bookShelfInfoEntityCustomer.getCode());
			//书籍投放数量
			Integer originalBookCount = bookEntityDao.queryOriginalBookCount(bookShelfInfoEntityCustomer.getCode());
			//书籍在借数量
			Integer borrowedBookCount = bookEntityDao.queryBorrowedBookCount(bookShelfInfoEntityCustomer.getCode());
			/*List<BookgridInfoEntity> bookgridInfoEntitys = bookgridInfoDao.queryGridCountByShelfCode(bookshelfInfoEntity.getCode());
			
			if(bookgridInfoEntitys!=null&&bookgridInfoEntitys.size()>0) {
				int normalStatus = 0;
				for(BookgridInfoEntity bookgridInfoEntity:bookgridInfoEntitys) {
					if(bookgridInfoEntity.getDamageReport()==null||bookgridInfoEntity.getDamageReport()==0) {
						normalStatus+=1;
					}
				}
				bookShelfEntityCustomer.setDisparkCount(normalStatus, bookgridInfoEntitys.size());
			}*/
			bookShelfInfoEntityCustomer.setCurrentCount(currentBookCount);
			bookShelfInfoEntityCustomer.setOriginalCount(originalBookCount);
			bookShelfInfoEntityCustomer.setBorrowedCount(borrowedBookCount);
		}
		return bookshelfInfoEntities;
	}

	@Override
	public int queryTotal(Query query) {
		return bookshelfInfoDao.queryTotal(query);
	}

	@Override
	public void updateBookGridStatus(BookGridsStatus bookGridsStatus) {
		BookgridInfoEntity bookgridInfoEntityDb = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode1());
		if(bookgridInfoEntityDb.getDamageReport()!=bookGridsStatus.getStatus1()) {
			bookgridInfoEntityDb.setDamageReport(bookGridsStatus.getStatus1());
			bookgridInfoEntityDb.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb);
		}
		
		BookgridInfoEntity bookgridInfoEntityDb2 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode2());
		if(bookgridInfoEntityDb2.getDamageReport()!=bookGridsStatus.getStatus2()) {
			bookgridInfoEntityDb2.setDamageReport(bookGridsStatus.getStatus2());
			bookgridInfoEntityDb2.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb2);
		}
		BookgridInfoEntity bookgridInfoEntityDb3 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode3());
		if(bookgridInfoEntityDb3.getDamageReport()!=bookGridsStatus.getStatus3()) {
			bookgridInfoEntityDb3.setDamageReport(bookGridsStatus.getStatus3());
			bookgridInfoEntityDb3.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb3);
		}
		
		BookgridInfoEntity bookgridInfoEntityDb4 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode4());
		if(bookgridInfoEntityDb4.getDamageReport()!=bookGridsStatus.getStatus4()) {
			bookgridInfoEntityDb4.setDamageReport(bookGridsStatus.getStatus4());
			bookgridInfoEntityDb4.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb4);
		}
		BookgridInfoEntity bookgridInfoEntityDb5 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode5());
		if(bookgridInfoEntityDb5.getDamageReport()!=bookGridsStatus.getStatus5()) {
			bookgridInfoEntityDb5.setDamageReport(bookGridsStatus.getStatus5());
			bookgridInfoEntityDb5.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb5);
		}
		BookgridInfoEntity bookgridInfoEntityDb6 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode6());
		if(bookgridInfoEntityDb6.getDamageReport()!=bookGridsStatus.getStatus6()) {
			bookgridInfoEntityDb6.setDamageReport(bookGridsStatus.getStatus6());
			bookgridInfoEntityDb6.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb6);
		}
		BookgridInfoEntity bookgridInfoEntityDb7 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode7());
		if(bookgridInfoEntityDb7.getDamageReport()!=bookGridsStatus.getStatus7()) {
			bookgridInfoEntityDb7.setDamageReport(bookGridsStatus.getStatus7());
			bookgridInfoEntityDb7.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb7);
		}
		BookgridInfoEntity bookgridInfoEntityDb8 = bookgridInfoDao.queryObject(bookGridsStatus.getBookGridCode8());
		if(bookgridInfoEntityDb8.getDamageReport()!=bookGridsStatus.getStatus8()) {
			bookgridInfoEntityDb8.setDamageReport(bookGridsStatus.getStatus8());
			bookgridInfoEntityDb8.setModifyTime(new Date());
			bookgridInfoDao.update(bookgridInfoEntityDb8);
		}
		
	}

	@Override
	public List<BookgridInfoEntity> getBookGridsByShelfCode(String code) {
		return bookgridInfoDao.queryGridCountByShelfCode(code);
	}

	@Override
	public WebResponse openCloseBookGrid(BookGridsStatus bookGridsStatus) {
		
		return null;
	}

	@Override
	public BookShelfInfoEntityCustomer getBookShelfInfo(String code) {
		BookshelfInfoEntity bookshelfInfoEntity = bookshelfInfoDao.queryObject(code);
		BookShelfInfoEntityCustomer bookShelfEntityCustomer = new BookShelfInfoEntityCustomer();
		BeanUtils.copyProperties(bookshelfInfoEntity, bookShelfEntityCustomer);
		bookShelfEntityCustomer.setCashAddress(bookshelfInfoEntity.getAddress()+bookshelfInfoEntity.getArea());
		//获取书格数量
		List<BookgridInfoEntity> bookgridInfoEntitys = bookgridInfoDao.queryGridCountByShelfCode(bookshelfInfoEntity.getCode());
		bookShelfEntityCustomer.setBookGridCount(bookgridInfoEntitys.size());
		//当前实际书本总数
		bookShelfEntityCustomer.setCurrentCount(bookEntityDao.queryCurrentBookCount(bookshelfInfoEntity.getCode()));
		return bookShelfEntityCustomer;
	}

	@Override
	public List<BookEntityCustomer> getBookGridInfo(Query query) {
		PageHelper.startPage(PageHelperUtil.getPageNum(query),PageHelperUtil.getPageSize(query));
		BookEntityEntity bookEntityEntity = new BookEntityEntity();
		bookEntityEntity.setCurrentGridCode(query.get("bookGridCode").toString());
		if(query.get("newGridCode")!=null) {
			bookEntityEntity.setCurrentGridCode(query.get("newGridCode").toString());
		}
		return bookEntityDao.queryBooksByGridCode(bookEntityEntity.getCurrentGridCode());
	}

	@Override
	public WebResponse unlock(String bookGridId) {
		WebResponse webResponse = new WebResponse();
		BookGridTransEntity bookGridTransEntity = new BookGridTransEntity();
		BookgridInfoEntity bookgridInfoEntityDb = bookgridInfoDao.queryObject(bookGridId);
		String gridPostfix = bookGridId.substring(10);
		try {
			if(bookgridInfoEntityDb.getLockStatus() == 1) {
				webResponse.setCode(ResponseEnum.BOOK_GRID_OPEN.getCode());
				webResponse.setMessage(ResponseEnum.BOOK_GRID_OPEN.getMessage());
				return webResponse;
			}
			if (bookgridInfoEntityDb.getLockStatus() == 0 || bookgridInfoEntityDb.getLockStatus() == 4
					|| bookgridInfoEntityDb.getLockStatus() == 3) {
				webResponse.setCode(ResponseEnum.UNLOCK_GRID_STATUS_ERROR.getCode());
				webResponse.setMessage(ResponseEnum.UNLOCK_GRID_STATUS_ERROR.getMessage());
				return webResponse;
			}
			bookgridInfoEntityDb.setModifyTime(new Date());
			bookgridInfoEntityDb.setLockStatus(0);// 更改书格资料表中书格状态为请求打开
			bookgridInfoDao.update(bookgridInfoEntityDb);
			// 记录书格变化流水
			bookGridTransEntity.setCreateTime(new Date());
			bookGridTransEntity.setGridCode(bookGridId);
			bookGridTransEntity.setLockStatus(0);
			bookGridTransEntity.setUserId(12238l);
			bookGridTransEntity.setUserType(1);
			bookGridTransDao.save(bookGridTransEntity);
			Long maxGroupId = bookGridManager.notifyBookGrid(bookGridId, 1L, WSBookShelfEnum.bookgrid_unlock_req);
			logger.info("单书格打开柜门返回回来的groupId值为:\t"+maxGroupId);
			Date date = new Date();
			ProcessInstructionLogDO instructionLogDO = new ProcessInstructionLogDO();
			instructionLogDO.setAction(WSBookShelfEnum.bookgrid_status_res+"");
			instructionLogDO.setInstructionGroupId(maxGroupId);
			instructionLogDO.setInstructionId(4);
			Boolean checkResult = false;//盘点结果
			Boolean circulationFlag = true;//循环标识
			Boolean timeOutFlag = false;
			ProcessInstructionLogDO do1 = null;
			while(circulationFlag) {
				if(do1==null) {
					do1 = processInstructionLogDAO.getActionResponse(instructionLogDO);
				}
				if(do1!=null) {
					checkResult = true;
					if(timeOutFlag) {
						circulationFlag = false;
					}
				}else {
					timeOutFlag = this.pastTimeFlagFives(date,5l);
					if(timeOutFlag) {
						circulationFlag = false;
					}
				}
				Thread.sleep(1000l);
			}
			if(checkResult) {
				bookgridInfoEntityDb.setLockStatus(1);// 更改书格资料表中书格状态为已打开
				bookgridInfoDao.update(bookgridInfoEntityDb);
				// 更改书格变化流水表中状态，并记录
				bookGridTransEntity.setLockStatus(1);// 更改书格变化流水表中书格状态为已打开
				bookGridTransDao.save(bookGridTransEntity);
				webResponse.setCode(100);
				webResponse.setMessage(gridPostfix+"号开柜成功");
			}
			if(timeOutFlag) {
				webResponse.setCode(ResponseEnum.BOOK_GRID_OPEN_TIMEOUT.getCode());
				webResponse.setMessage(ResponseEnum.BOOK_GRID_OPEN_TIMEOUT.getMessage());
			}
			return webResponse;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			bookgridInfoEntityDb.setLockStatus(2);// 更改书格资料表中书格状态为打开失败
			bookgridInfoDao.update(bookgridInfoEntityDb);
			// 更改书格变化流水表中状态，并记录
			bookGridTransEntity.setLockStatus(2);// 更改书格变化流水表中书格状态为打开失败
			bookGridTransDao.save(bookGridTransEntity);
			webResponse.setCode(ResponseEnum.UNLOCK_GRID_FAIL.getCode());
			webResponse.setMessage(gridPostfix+ResponseEnum.UNLOCK_GRID_FAIL.getMessage());
			return webResponse;
		}
	}

	@Override
	public WebResponse checkBookGridOne(String bookgridCode) {
		WebResponse webResponse = new WebResponse();
		BookgridInfoEntity bookgridInfoEntityDb = bookgridInfoDao.queryObject(bookgridCode);
		String gridPostfix = bookgridCode.substring(10);
		try {
			if (bookgridInfoEntityDb.getLockStatus() == 2 || bookgridInfoEntityDb.getLockStatus() == 5) {
				Long maxGroupId = bookGridManager.notifyBookGrid(bookgridCode, null, WSBookShelfEnum.bookgrid_check_req);
				logger.info("单书格盘点返回的groupId值为:\t"+maxGroupId);
				Date date = new Date();
				ProcessInstructionLogDO instructionLogDO = new ProcessInstructionLogDO();
				instructionLogDO.setAction(WSBookShelfEnum.bookgrid_check_res+"");
				instructionLogDO.setInstructionGroupId(maxGroupId);
				//instructionLogDO.setInstructionId(2);
				Boolean checkResult = false;//盘点结果
				Boolean flag = true;//循环标识
				Boolean timeOutFlag = false;
				ProcessInstructionLogDO do1 = null;
				while(flag) {
					do1 = processInstructionLogDAO.getActionResponse(instructionLogDO);
					if(do1!=null) {
						checkResult = true;
						flag = false;
					}else {
						timeOutFlag = this.pastTimeFlagFives(date,5l);
						if(timeOutFlag) {
							flag = false;
						}
					}
					Thread.sleep(1000l);
				}
				if(checkResult) {
					webResponse.setCode(100);
					webResponse.setMessage(do1.getContent());
				}
				if(timeOutFlag) {
					webResponse.setCode(ResponseEnum.REFRESH_GRID_RES_ERROR.getCode());
					webResponse.setMessage(ResponseEnum.REFRESH_GRID_RES_ERROR.getMessage());
				}
				return webResponse;
			}else {
				webResponse.setCode(ResponseEnum.REFRESH_GRID_STATUS_ERROR.getCode());
				webResponse.setMessage(ResponseEnum.REFRESH_GRID_STATUS_ERROR.getMessage());
				return webResponse;
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			webResponse.setCode(ResponseEnum.UNLOCK_GRID_FAIL.getCode());
			webResponse.setMessage(gridPostfix+ResponseEnum.UNLOCK_GRID_FAIL.getMessage());
			return webResponse;
		}
	}

	@Override
	public WebResponse restart(String bookshelfCode) {
		WebResponse webResponse = new WebResponse();
		//查询书柜所有书格状态
		try {
			List<BookgridInfoEntity> bookgridInfoEntities = bookgridInfoDao.queryGridCountByShelfCode(bookshelfCode);
			for(BookgridInfoEntity bookgridInfoEntity:bookgridInfoEntities) {
				if(!(bookgridInfoEntity.getLockStatus()==2||bookgridInfoEntity.getLockStatus()==5)) {
					webResponse.setCode(ResponseEnum.RESTART_SHELF_STATUS_ERROR.getCode());
					webResponse.setMessage(ResponseEnum.RESTART_SHELF_STATUS_ERROR.getMessage());
					return webResponse;
				}
			}
			bookGridManager.notifyBookGrid(bookshelfCode+"01", 1L, WSBookShelfEnum.bookcase_restart);
			webResponse.setCode(100);
			webResponse.setMessage(bookshelfCode+"号柜子发送重启命令成功");
			return webResponse;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			webResponse.setCode(ResponseEnum.RESTART_SHELF_ERROR.getCode());
			webResponse.setMessage(bookshelfCode+ResponseEnum.RESTART_SHELF_ERROR.getMessage());
			return webResponse;
		}
	}

	@Override
	public WebResponse checkBookGridAll(String bookShelfCode) {
		/*WebResponse webResponse = new WebResponse();
		try {
			List<BookgridInfoEntity> bookgridInfoEntities = bookgridInfoDao.queryGridCountByShelfCode(bookShelfCode);
			boolean flag = true;
			for(BookgridInfoEntity bookgridInfoEntity:bookgridInfoEntities) {
				if(!(bookgridInfoEntity.getLockStatus()==2||bookgridInfoEntity.getLockStatus()==5)) {
					flag = false;
					webResponse.setCode(ResponseEnum.CHECK_ALL_SHELF_STATUS_ERROR.getCode());
					webResponse.setMessage(ResponseEnum.CHECK_ALL_SHELF_STATUS_ERROR.getMessage());
					return webResponse;
				}
			}
			bookGridManager.notifyBookGrid(bookShelfCode+"01", 1L, WSBookShelfEnum.bookcase_check_req);
			webResponse.setCode(100);
			webResponse.setMessage(bookShelfCode+"整柜盘点请求发送成功");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			webResponse.setCode(ResponseEnum.CHECK_ALL_SHELF_SEND_ERROR.getCode());
			webResponse.setMessage(bookShelfCode+ResponseEnum.CHECK_ALL_SHELF_SEND_ERROR.getMessage());
		}
		return webResponse;*/
		WebResponse webResponse = new WebResponse();
		try {
			List<BookgridInfoEntity> bookgridInfoEntities = bookgridInfoDao.queryGridCountByShelfCode(bookShelfCode);
			for(BookgridInfoEntity bookgridInfoEntity:bookgridInfoEntities) {
				if(!(bookgridInfoEntity.getLockStatus()==2||bookgridInfoEntity.getLockStatus()==5)) {
					webResponse.setCode(ResponseEnum.CHECK_ALL_SHELF_STATUS_ERROR.getCode());
					webResponse.setMessage(ResponseEnum.CHECK_ALL_SHELF_STATUS_ERROR.getMessage());
					return webResponse;
				}
			}
			Long maxGroupId = bookGridManager.notifyBookGrid(bookShelfCode+"01", 1L, WSBookShelfEnum.bookcase_check_req);
			logger.info("全柜盘点返回groupId值为:\t"+maxGroupId);
			Date date = new Date();
			ProcessInstructionLogDO instructionLogDO = new ProcessInstructionLogDO();
			instructionLogDO.setAction(WSBookShelfEnum.bookcase_check_res+"");
			instructionLogDO.setInstructionGroupId(maxGroupId);
			//instructionLogDO.setInstructionId(2);
			Boolean checkResult = false;//盘点结果
			Boolean circulationFlag = true;//循环标识
			Boolean timeOutFlag = false;
			ProcessInstructionLogDO do1 = null;
			while(circulationFlag) {
				do1 = processInstructionLogDAO.getActionResponse(instructionLogDO);
				if(do1!=null) {
					checkResult = true;
					circulationFlag = false;
				}else {
					timeOutFlag = this.pastTimeFlagFives(date,60l);
					if(timeOutFlag) {
						circulationFlag = false;
					}
				}
				Thread.sleep(1000l);
			}
			if(checkResult) {
				webResponse.setCode(100);
				webResponse.setMessage(do1.getContent());
			}
			if(timeOutFlag) {
				webResponse.setCode(ResponseEnum.REFRESH_GRID_RES_ERROR.getCode());
				webResponse.setMessage(ResponseEnum.REFRESH_GRID_RES_ERROR.getMessage());
			}
			return webResponse;
		} catch (Exception e) {
			webResponse.setCode(ResponseEnum.CHECK_ALL_SHELF_SEND_ERROR.getCode());
			webResponse.setMessage(bookShelfCode+ResponseEnum.CHECK_ALL_SHELF_SEND_ERROR.getMessage());
			return webResponse;
		}
	}
	private Boolean pastTimeFlagFives(Date sendTime,long timeout) {
		Date date = new Date();
		Long endTime = date.getTime();
		Long startTime = sendTime.getTime();
		long diff = endTime - startTime;
		long seconds = diff / 1000 ;
		return seconds>timeout?true:false;
	}
	private DaysQueryRequest initQueryRequest(DaysQueryRequest daysQueryRequest) {
		Date date = new Date();
		Date queryEndTime = daysQueryRequest.getQueryEndTime();
		if(queryEndTime==null) {
			queryEndTime = date;
			daysQueryRequest.setQueryEndTime(date);
		}
		Date originalQueryEndTime = daysQueryRequest.getQueryEndTime();
		daysQueryRequest.setOriginalQueryEndTime(originalQueryEndTime);
		
		Date originalQueryStartTime = daysQueryRequest.getQueryStartTime();
		daysQueryRequest.setOriginalQueryStartTime(originalQueryStartTime);
		return daysQueryRequest;
	}
	@Override
	public List<OperationResponse> bookShelfCurrentCondition(DaysQueryRequest daysQueryRequest) {
		this.initQueryRequest(daysQueryRequest);
		List<OperationResponse> list = new ArrayList<OperationResponse>();
		//查询书柜保修状态
		List<BookgridInfoEntity> bookgridInfoEntities = bookgridInfoDao.queryGridCountByShelfCode(daysQueryRequest.getBookShelfCode());
		StringBuffer buffer = new StringBuffer();
		StringBuffer availableBuff = new StringBuffer();
		for(BookgridInfoEntity bookgridInfoEntity:bookgridInfoEntities) {
			if(bookgridInfoEntity.getDamageReport()==1) {
				if(buffer.length()>0) {
					buffer.append(",");
				}
				buffer.append(bookgridInfoEntity.getBookgridCode().substring(10));
			}
			if(bookgridInfoEntity.getAvailable()==0) {
				if(availableBuff.length()>0) {
					availableBuff.append(",");
				}
				availableBuff.append(bookgridInfoEntity.getBookgridCode().substring(10));
			}
		}
		//机柜报修状态
		OperationResponse bookShelfStatusResponse = new OperationResponse();
		bookShelfStatusResponse.setKey("机柜状态");
		OperationResponse bookShelfMaintainResponse = new OperationResponse();
		bookShelfMaintainResponse.setKey("柜门报修");
		if(buffer.length()<1&&availableBuff.length()<1) {
			bookShelfStatusResponse.setValue("正常");
			bookShelfStatusResponse.setStatus("0");
			bookShelfMaintainResponse.setValue("无");
			bookShelfStatusResponse.setStatus("0");
		}
		if(buffer.length()>0&&availableBuff.length()<1) {
			bookShelfStatusResponse.setValue("报修");
			bookShelfStatusResponse.setStatus("1");
			bookShelfMaintainResponse.setValue(buffer.toString());
			bookShelfStatusResponse.setStatus("1");
		}
		if(availableBuff.length()>0) {
			bookShelfStatusResponse.setValue("维修");
			bookShelfStatusResponse.setStatus("1");
			bookShelfMaintainResponse.setValue(availableBuff.toString());
			bookShelfStatusResponse.setStatus("1");
		}
		list.add(bookShelfStatusResponse);
		//柜门报修
		list.add(bookShelfMaintainResponse);
		//柜门灯状态
		OperationResponse bookShelfLampResponse = new OperationResponse();
		bookShelfLampResponse.setKey("柜门灯状态");
		bookShelfLampResponse.setValue("暂无数据");
		list.add(bookShelfLampResponse);
		//已投放书籍总计
		String countBorrowBooks = orderTransDao.countBorrowBooks(daysQueryRequest);
		OperationResponse bookShelfBorrowBooksResponse = new OperationResponse();
		bookShelfBorrowBooksResponse.setKey("已投放书籍总计");
		bookShelfBorrowBooksResponse.setValue(countBorrowBooks);
		list.add(bookShelfBorrowBooksResponse);
		//在柜书籍
		Integer booksCount = bookEntityDao.queryCurrentBookCount(daysQueryRequest.getBookShelfCode());
		OperationResponse bookShelfBooksCountResponse = new OperationResponse();
		bookShelfBooksCountResponse.setKey("在柜书籍");
		bookShelfBooksCountResponse.setValue(booksCount+"");
		list.add(bookShelfBooksCountResponse);
		//网络状态
		OperationResponse networkResponse = new OperationResponse();
		networkResponse.setKey("网络状态");
		networkResponse.setValue("数据暂无");
		list.add(networkResponse);
		return list;
	}

	@Override
	public WebResponse lampStrategy(BookShelfOperation bookShelfOperation) {
		WebResponse webResponse = new WebResponse();
		try {
			String jsonMsg = this.policiesIssued(bookShelfOperation);
			bookGridManager.lampStrategy(jsonMsg);
			LampStrategyEntity lampStrategyEntity = new LampStrategyEntity();
			lampStrategyEntity.setBookShelfCode(bookShelfOperation.getBookShelfCode());
			lampStrategyEntity.setCreateTime(new Date());
			String ledEndStr = DateFormatUtil.formateDateToString(bookShelfOperation.getLedEnd(), DateFormatUtil.TIME_PATTERN_NO_COLON);
			String ledStartStr = DateFormatUtil.formateDateToString(bookShelfOperation.getLedStart(), DateFormatUtil.TIME_PATTERN_NO_COLON);
			lampStrategyEntity.setSumLedEnd(ledEndStr);
			lampStrategyEntity.setSumLedStart(ledStartStr);
			lampStrategyEntity.setWinLedStart(ledStartStr);
			lampStrategyEntity.setWinLedEnd(ledEndStr);
			StringBuffer buffer = new StringBuffer();
			if(bookShelfOperation.getUvlampTimes()!=null) {
				for(Date s:bookShelfOperation.getUvlampTimes()) {
					if(buffer.length()>0) {
						buffer.append(",");
					}
					buffer.append(DateFormatUtil.formateDateToString(s, DateFormatUtil.TIME_PATTERN_NO_COLON));
				}
			}
			lampStrategyEntity.setUvlampTimes(buffer.toString());
			lampStrategyEntity.setUmlampLength(bookShelfOperation.getUmlampLength());
			lampStrategyEntity.setUmlampLength("60");
			SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
			lampStrategyEntity.setUserId(sysUserEntity==null?null:sysUserEntity.getUserId());
			lampStrategyDao.save(lampStrategyEntity);
			webResponse.setCode(100);
			webResponse.setMessage("书柜灯光策略设置成功");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			webResponse.setCode(400);
			webResponse.setMessage(bookShelfOperation.getBookShelfCode()+"号书柜灯光策略设置失败");
		}
		return webResponse;
	}
	private String policiesIssued(BookShelfOperation bookShelfOperation) {
		String ledEndStr = DateFormatUtil.formateDateToString(bookShelfOperation.getLedEnd(), DateFormatUtil.TIME_PATTERN_NO_COLON);
		String ledStartStr = DateFormatUtil.formateDateToString(bookShelfOperation.getLedStart(), DateFormatUtil.TIME_PATTERN_NO_COLON);
		JSONObject info = new JSONObject();
		info.put("interval", 4);
		List<String> statusCheckList = new ArrayList<String>();
		statusCheckList.add("0000");
		statusCheckList.add("0600");
		statusCheckList.add("0900");
		info.put("statusCheck", statusCheckList);
		
		List<String> bookCheckList = new ArrayList<String>();
		bookCheckList.add("0000");
		bookCheckList.add("0600");
		bookCheckList.add("0900");
		info.put("bookCheck", bookCheckList);
		
		info.put("reserve", 4);
		
		List<String> uvlamp_start = new ArrayList<String>();
		int size = 0;
		if(bookShelfOperation.getUvlampTimes()!=null) {
			size = bookShelfOperation.getUvlampTimes().size();
			for(Date time:bookShelfOperation.getUvlampTimes()) {
				uvlamp_start.add(DateFormatUtil.formateDateToString(time, DateFormatUtil.TIME_PATTERN_NO_COLON));
			}
		}
		try {
			String createTime = "";
			String timeA = "";
			String timeB = "";
			String timeC = "";
			SimpleDateFormat simpleDateFormatMi = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
			switch (size) {
			case 0:
				uvlamp_start.add("0000");
				uvlamp_start.add("0000");
				uvlamp_start.add("0000");
				createTime = DateFormatUtil.formateDateToString(new Date(), DateFormatUtil.DATE_PATTERN);
				timeA = createTime + "-00-00";
				timeB = createTime + "-00-00";
				timeC = createTime + "-00-00";
				List<Date> uvlampTimes = new ArrayList<>();
				uvlampTimes.add(simpleDateFormatMi.parse(timeA));
				uvlampTimes.add(simpleDateFormatMi.parse(timeB));
				uvlampTimes.add(simpleDateFormatMi.parse(timeC));
				bookShelfOperation.setUvlampTimes(uvlampTimes);
				break;
			case 1:
				uvlamp_start.add("0000");
				uvlamp_start.add("0000");
				createTime = DateFormatUtil.formateDateToString(new Date(), DateFormatUtil.DATE_PATTERN);
				timeA = createTime + "-00-00";
				timeC = createTime + "-00-00";
				uvlampTimes = bookShelfOperation.getUvlampTimes();
				uvlampTimes.add(simpleDateFormatMi.parse(timeA));
				uvlampTimes.add(simpleDateFormatMi.parse(timeC));
				bookShelfOperation.setUvlampTimes(uvlampTimes);
				break;
			case 2:
				uvlamp_start.add("0000");
				createTime = DateFormatUtil.formateDateToString(new Date(), DateFormatUtil.DATE_PATTERN);
				timeA = createTime + "-00-00";
				uvlampTimes = bookShelfOperation.getUvlampTimes();
				uvlampTimes.add(simpleDateFormatMi.parse(timeA));
				bookShelfOperation.setUvlampTimes(uvlampTimes);
				break;
			default:
				break;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		/*uvlamp_start.add("2100");
		uvlamp_start.add("2130");
		uvlamp_start.add("2200");*/
		info.put("uvlamp_start", uvlamp_start);
		
		//info.put("uvlamp_keep", bookShelfOperation.getUmlampLength());
		info.put("uvlamp_keep", 60);
		
		List<String> led_start_end = new ArrayList<String>();
		String sumTime = ledStartStr+"-"+ledEndStr;
		led_start_end.add(sumTime);
		String winTime = ledStartStr+"-"+ledEndStr;
		led_start_end.add(winTime);
		//led_start_end.add("1600-1800");
		//led_start_end.add("1600-1800");
		info.put("led_start_end", led_start_end);
		
		JSONObject data = new JSONObject();
		data.put("action", "policies_issued");
		data.put("info", info);
		//data.put("bookCaseId", "0021200016");
		data.put("bookCaseId", bookShelfOperation.getBookShelfCode());
		System.out.println(data.toString());
		logger.info(data.toString());
		return data.toString();
	}

	@Override
	public LampStrategyRes lampStrategyCurrent(BookShelfOperation bookShelfOperation) {
		LampStrategyEntity lampStrategyEntity = lampStrategyDao.queryObjectByShelfCode(bookShelfOperation.getBookShelfCode());
		LampStrategyRes lampStrategyRes = new LampStrategyRes();
		if(lampStrategyEntity==null) {
			String createTime = DateFormatUtil.formateDateToString(new Date(), DateFormatUtil.DATE_PATTERN);
			lampStrategyRes.setBookShelfCode(bookShelfOperation.getBookShelfCode());
			lampStrategyRes.setLedEnd(createTime+"-23-00");
			lampStrategyRes.setLedStart(createTime+"-00-00");
			
			String timeA = createTime + "-07-00";
			String timeB = createTime + "-22-00";
			String timeC = createTime + "-03-00";
			List<String> uvlampTimes = new ArrayList<>();
			uvlampTimes.add(timeA);
			uvlampTimes.add(timeB);
			uvlampTimes.add(timeC);
			lampStrategyRes.setUvlampTimes(uvlampTimes);
			lampStrategyRes.setUmlampLength("60");
			lampStrategyRes.setStatus("0");
		}else {
			String createTimeStr = DateFormatUtil.formateDateToString(lampStrategyEntity.getCreateTime(), DateFormatUtil.DATE_PATTERN);
			String ledStartDb = lampStrategyEntity.getSumLedStart();
			String ledEndDb = lampStrategyEntity.getSumLedEnd();
			lampStrategyRes.setBookShelfCode(bookShelfOperation.getBookShelfCode());
			lampStrategyRes.setLedEnd(createTimeStr+"-"+ledEndDb.substring(0, 2)+"-"+ledEndDb.substring(2));
			lampStrategyRes.setLedStart(createTimeStr+"-"+ledStartDb.substring(0, 2)+"-"+ledStartDb.substring(2));
			List<String> list = new ArrayList<>();
			String uvlampTimesStr =lampStrategyEntity.getUvlampTimes();
			if(uvlampTimesStr!=null&&!uvlampTimesStr.equals("")) {
				for(String s:uvlampTimesStr.split(",")) {
					list.add(createTimeStr+"-"+s.substring(0,2)+"-"+s.substring(2));
				}
			}
			lampStrategyRes.setUvlampTimes(list);
			lampStrategyRes.setUmlampLength(lampStrategyEntity.getUmlampLength());
			lampStrategyRes.setStatus("1");
		}
		return lampStrategyRes;
	}

	@Override
	public List<BookShelfLoRes> bookShelfLogs(BookShelfOperation bookShelfOperation) {
		//查询每一次开柜的请求
		ProcessInstructionLogDO instructionLogDO = new ProcessInstructionLogDO();
		instructionLogDO.setBookgridCode(bookShelfOperation.getBookShelfCode());
		List<ProcessInstructionLogCustomer> dos = processInstructionLogDAO.instructionLogs(instructionLogDO);
		List<BookShelfLoRes> bookShelfLoRes = new ArrayList<BookShelfLoRes>();
		for(ProcessInstructionLogCustomer processInstructionLogCustomer:dos) {
			String json = processInstructionLogCustomer.getContent();
			ProcessCheckRes checkRes = JSONObject.parseObject(json,ProcessCheckRes.class);
			BookShelfLoRes loRes = new BookShelfLoRes();
			if(checkRes==null) {
				loRes.setCount("盘点数据有误");
			}else {
				loRes.setCount(checkRes.getData().size()+"");
			}
			loRes.setMobile(processInstructionLogCustomer.getMobileNo());
			loRes.setOperTime(DateFormatUtil.formatDate(processInstructionLogCustomer.getOperTime(), DateFormatUtil.DATETIME_PATTERN));
			bookShelfLoRes.add(loRes);
		}
		return bookShelfLoRes;
	}
}
